package com.bxd.baodan.base;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.fragment.BaseFragment;
import com.bxd.baodan.util.DialogUtil;

/**
 * 下拉刷新,上拉加载更多的fragment
 * 
 * @author oldfeel
 * 
 *         Created on: 2014年3月2日
 */
public abstract class BaseDBListFragment extends BaseFragment implements
		 OnScrollListener {
	protected BaseBaseAdapter<?> adapter;
	private int lastVisibleIndex;
	protected int page = 0;
	private ProgressBar progressBar;
	private PullToRefreshListView mPullRefreshListView;
	private ListView listView;
	private TextView tvEmpty;
	protected String emptyText = "哎，啥都没有~";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.base_db_list, container,
				false);
		mPullRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);
		listView = mPullRefreshListView.getRefreshableView();
		tvEmpty = (TextView) view.findViewById(R.id.base_list_empty);

		initListView();
		return view;
	}
	private void initListView() {
		mPullRefreshListView.setMode(Mode.BOTH);
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(
								App.getContext(),
								System.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						// Do work to autoRefresh the list here.
						if (mPullRefreshListView.isHeaderShown()) {
							// 下拉刷新
							page = 0;
							onRefreshStarted();
						} else if (mPullRefreshListView.isFooterShown()) {
							if(!adapter.isAddOver()){
								getData(++page);
							}else{
								new FreshCompleteTask().execute();
							}
						
						}
					}
				});

	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		progressBar = new ProgressBar(App.getContext());
		initAdapter();
		listView.setAdapter(adapter);
		listView.setOnScrollListener(this);
		listView.setOnCreateContextMenuListener(this);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				position = position - listView.getHeaderViewsCount();
				if (position >= 0) {
					BaseDBListFragment.this.onItemClick(position);
				}
			}
		});
		getData(0);
		setEmptyString();
		tvEmpty.setText(emptyText);
	}

	public abstract void setEmptyString();

	public ListView getListView() {
		return listView;
	}

	public void getData(final int page) {
		this.page = page;
		if (page != 0 && adapter.isAddOver()) {
			return;
		}
		adapter.getData(page);
		refreshComplete();
	}

	protected void refreshComplete() {
		if (adapter.getCount() < Constant.PAGE_SIZE) {
			if (isVisible() && listView != null && progressBar != null) {
				listView.removeFooterView(progressBar);
			}
		}
		if (adapter.getCount() == 0) {
			listView.setVisibility(View.GONE);
			tvEmpty.setVisibility(View.VISIBLE);
		}
		new FreshCompleteTask().execute();
	}

	public void onRefreshStarted() {
		getData(0);
	}
	private class FreshCompleteTask extends AsyncTask<Void, Void, String[]> {
		
		@Override
		protected String[] doInBackground(Void... params) {
			// Simulates a background job.
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(String[] result) {
			super.onPostExecute(result);
			mPullRefreshListView.onRefreshComplete();
		}
	}


	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
	}

	@Override
	public void showToast(String text) {
		DialogUtil.getInstance().showToast(App.getContext(), text);
	}

	public abstract void onItemClick(int position);

	public abstract void initAdapter();

	OnResultListener resultListener;

	public interface OnResultListener {
		public void setResult(String result);
	}

	public void setOnResultListener(OnResultListener resultListener) {
		this.resultListener = resultListener;
	}


	@Override
	public void startActivity(Intent intent) {
		super.startActivity(intent);
		if(getActivity()!=null){
			getActivity().overridePendingTransition(R.anim.slide_in_right,
					R.anim.slide_out_left);
		}
	}

}
